package com.youlai.boot.system.controller;

import com.youlai.boot.system.model.dto.ProductDTO;
import com.youlai.boot.system.model.dto.ShoppingInfo;
import com.youlai.boot.system.service.OrderService;
import lombok.RequiredArgsConstructor;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.youlai.boot.system.model.form.OrderForm;
import com.youlai.boot.system.model.query.OrderQuery;
import com.youlai.boot.system.model.vo.OrderVO;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.youlai.boot.common.result.PageResult;
import com.youlai.boot.common.result.Result;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import jakarta.validation.Valid;

import java.util.List;

/**
 * 订单管理前端控制层
 *
 * @author zhangyurun
 * @since 2025-03-20 20:33
 */
@Tag(name = "订单管理接口")
@RestController
@RequestMapping("/api/v1/orders")
@RequiredArgsConstructor
public class OrderController {
    private final OrderService orderService;

    @Operation(summary = "订单管理分页列表")
    @GetMapping("/page")
    @PreAuthorize("@ss.hasPerm('sys:order:query')")
    public PageResult<OrderVO> getOrderPage(OrderQuery queryParams) {
        IPage<OrderVO> result = orderService.getOrderPage(queryParams);
        return PageResult.success(result);
    }

    @Operation(summary = "新增订单管理")
    @PostMapping
    @PreAuthorize("@ss.hasPerm('sys:order:add')")
    public Result<Void> saveOrder(@RequestBody @Valid OrderForm formData) {
        boolean result = orderService.saveOrder(formData);
        return Result.judge(result);
    }

    @Operation(summary = "获取订单管理表单数据")
    @GetMapping("/{id}/form")
    @PreAuthorize("@ss.hasPerm('sys:order:edit')")
    public Result<OrderForm> getOrderForm(
            @Parameter(description = "订单管理ID") @PathVariable Long id) {
        OrderForm formData = orderService.getOrderFormData(id);
        return Result.success(formData);
    }

    @Operation(summary = "修改订单管理")
    @PutMapping(value = "/{id}")
    @PreAuthorize("@ss.hasPerm('sys:order:edit')")
    public Result<Void> updateOrder(
            @Parameter(description = "订单管理ID") @PathVariable Long id,
            @RequestBody @Validated OrderForm formData) {
        boolean result = orderService.updateOrder(id, formData);
        return Result.judge(result);
    }

    @Operation(summary = "删除订单管理")
    @DeleteMapping("/{ids}")
    @PreAuthorize("@ss.hasPerm('sys:order:delete')")
    public Result<Void> deleteOrders(
            @Parameter(description = "订单管理ID，多个以英文逗号(,)分割") @PathVariable String ids) {
        boolean result = orderService.deleteOrders(ids);
        return Result.judge(result);
    }

    /**
     * 生成订单（未支付）
     *
     * @param shoppingInfo
     * @return
     */
    @PostMapping("/generateOrder")
    public Result<Long> generateOrder(@RequestBody ShoppingInfo shoppingInfo) {
        // 验证购物车是否为空
        if (shoppingInfo.getShoppingCart() == null || shoppingInfo.getShoppingCart().isEmpty()) {
            return Result.failed("购物车为空");
        }

        try {
            // 直接调用Service层方法，在Service层对每个商品单独加锁
            Long orderId = orderService.generateOrder(shoppingInfo);
            return Result.success(orderId);
        } catch (Exception e) {
            return Result.failed("订单生成失败：" + e.getMessage());
        }
    }

    /**
     * 结算订单（支付）
     *
     * @param orderId
     * @return
     */
    @PostMapping("/settleOrder/{orderId}")
    public Result<Void> settleOrder(@PathVariable("orderId") Long orderId) {
        orderService.settleOrder(orderId);
        return Result.success();
    }

    /**
     * 获取订单管理详情(为发货)
     *
     */
    @Operation(summary = "获取订单管理表单数据(为发货)")
    @GetMapping("/{id}/form-deliver")
    public Result<OrderForm> getOrderFormForDeliver(
            @Parameter(description = "订单管理ID") @PathVariable Long id) {
        OrderForm formData = orderService.getOrderFormData(id);
        return Result.success(formData);
    }

    /**
     * 发货
     *
     * @param formData
     * @return
     */
    @PostMapping("/shipments")
    public Result<Void> shipments(@RequestBody @Validated OrderForm formData) {
        orderService.shipments(formData);
        return Result.success();
    }

    /**
     * 确认收货
     *
     * @param orderId
     */
    @PostMapping("/confirmReceipt/{orderId}")
    public Result<Void> confirmReceipt(@PathVariable("orderId") Long orderId) {
        orderService.confirmReceipt(orderId);
        return Result.success();
    }

    /**
     * 手动取消订单
     *
     * @param orderId
     * @return
     */
    @PostMapping("/cancelOrder/{orderId}")
    public Result<Void> cancelOrder(@PathVariable("orderId") Long orderId) {
        orderService.cancelOrder(orderId);
        return Result.success();
    }

    /**
     * 查看商品列表
     * 
     * @param orderId
     * @return
     */
    @GetMapping("/viewProductList/{orderId}")
    public Result<List<ProductDTO>> viewProductList(@PathVariable("orderId") Long orderId) {
        List<ProductDTO> list = orderService.viewProductList(orderId);
        return Result.success(list);
    }
}
